/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.client.ui.login1;

import com.alibaba.fastjson.JSON;
import com.jili.ubert.client.ui.AbstractNodeUI;
import com.jili.ubert.client.ui.UINode;
import com.jili.ubert.client.ui.i18n.I18N;
import com.jili.ubert.clientapi.until.AnswerHandler;
import com.jili.ubert.clientapi.ClientAPI;
import com.jili.ubert.code.client2server.Login;
import com.jili.ubert.code.server2client.MsgResult;
import com.jili.ubert.until.VerifyCodeImageGenerator;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javafx.scene.input.MouseEvent;

/**
 * FXML Controller class
 *
 * @author ChengJiLi
 */
public class LoginUIController extends AbstractNodeUI implements Initializable {

    ClientAPI clientapi;
    String verword;
    private final AnswerHandler<String> handler = new AnswerHandler<String>() {
        @Override
        public void OnAnswer(String anwer) {
            log.info("验证码为：" + anwer);
            verword = anwer;
            int w = 100, h = 40;
            try {
                ByteArrayOutputStream out = VerifyCodeImageGenerator.getImageCode(w, h, verword);
                InputStream in = new ByteArrayInputStream(out.toByteArray());
                login_Image.setImage(new Image(in));

            } catch (IOException ex) {
                log.info(ex);
            }
        }

        @Override
        public void IsSuccess() {
        }

        @Override
        public void IsFalse(MsgResult rst) {
        }
    };
    private static final Log log = LogFactory.getLog(LoginUIController.class);
//extends AbstractNodeUI

    public LoginUIController(ClientAPI clientapi) {
        super(LoginUIController.class.getResource("LoginUI.fxml"), I18N.getBundle());
        this.clientapi = clientapi;
        log.info("LoginUIController初始化");
    }

    /**
     * Initializes the controller class.
     */
    /**
     * Initializes the controller class.
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        log.debug(url + "初始化");
        // TODO
        //  root=super.getUINode();
        //获取验证码
        MsgResult ret;
        ret = clientapi.ConnectTradeServer("127.0.0.1", 3773);
        if (ret.isSuccess()) {
            log.info("登陆成功，开始界面");
            clientapi.getVerlidCode(handler);
            login_Version.setText("连接服务器成功");
        } else {
            log.info("登陆失败");
            login_Version.setText("连接服务器失败");
        }

        login_Image.setOnMouseClicked((MouseEvent me) -> {
            log.debug("刷新验证码");
            clientapi.getVerlidCode(handler);
            me.consume();
        });
        /*
         login_Code.setOnKeyReleased((KeyEvent event) -> {
         if (login_Code.getText().equals(verword)) {
         login_Status.setText("验证码错误");
         }
         event.consume();
         });
         */

    }

    @FXML
    private PasswordField login_PassWord;

    @FXML
    private Button login_button;

    @FXML
    private Label login_Status;

    @FXML
    private ProgressIndicator login_Prograss;

    @FXML
    private ComboBox<String> login_UserID;

    @FXML
    private Label login_Version;

    @FXML
    private TextField login_Code;

    @FXML
    private ImageView login_Image;
    /*
     @FXML
     void OnCheckVerCode(ActionEvent event) {
     if (login_Code.getText().equals(verword)) {
     login_Status.setText("验证码错误");
     }
     event.consume();
     }
     */

    @FXML
    void LoginAction(ActionEvent event) throws IOException {
        Login login = new Login();
        login.setUserID(login_UserID.getValue());
        login.setPWD(login_PassWord.getText());
        login.setCode(login_Code.getText());
        log.info(JSON.toJSONString(event) + "  " + JSON.toJSONString(login));
        if (clientapi != null) {
            clientapi.LoginTradeServer(login, loginhandler);
        } else {
            //请配置线路，弹出线路代理的配置地址；
        }
        event.consume();
    }
    private final AnswerHandler<MsgResult> loginhandler = new AnswerHandler<MsgResult>() {
        @Override
        public void OnAnswer(MsgResult anwer) {
//            log.debug("登陆回报：" + JSON.toJSONString(anwer));
            Platform.runLater(() -> {
                if (anwer.getSuccess()) {

                    UINode.getStage().close();
                    Stage stage1 = new Stage();
                    UINode.setStage(stage1);
                    Scene scene1 = new Scene(UINode.getWorkSpace(clientapi).getUINode());
                    stage1.setScene(scene1);
                    stage1.initStyle(StageStyle.DECORATED);
                    log.info(stage1.getStyle().getClass());
                    stage1.show();

                } else {
                    login_Status.setText("错误代码：" + anwer.getReturnID() + ":" + anwer.getWord());
                    if (anwer.getReturnID() == 1) {//用户名不存在

                    } else if (anwer.getReturnID() == 2) {//密码不对

                    } else {//其他错误

                    }
                }
            });
        }

        @Override
        public void IsSuccess() {
        }

        @Override
        public void IsFalse(MsgResult rst) {
        }


    };
}
